/*
**********************************************************************************
    OpenSURF642 : An TI DM642 implementation of OpenSURF.
    Copyright (C) 2011  Hai Yu

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
	This implementation is based on The original OpenSURF library created
	by Christopher Evans.The original work can be found at
		http://www.chrisevansdev.com/computer-vision-opensurf.html
	
    contact: yuhaihai12345@gmail.com	
**********************************************************************************
*/

#ifndef _OPEN_SURF_642_UTIL_
#define _OPEN_SURF_642_UTIL_

#include "tistdtypes.h"

#ifndef _TI_ENHANCED_MATH_H
#define _TI_ENHANCED_MATH_H
#endif
#include "math.h"

/***********    Definition of image structures  ***************************/
typedef struct
{
	Uint8 * data;
	Uint16 lines;
	Uint16 pixels_per_line;
} Uimage8;

typedef struct
{
	Uint16 * data;
	Uint16 lines;
	Uint16 pixels_per_line;
}Uimage16;

typedef struct
{
	Uint32 * data;
	Uint16 lines;
	Uint16 pixels_per_line;
}Uimage32;



typedef Uint32   IntegralDataType;
typedef Uimage32 IntegralImage;




/***************   Util Functions   ********************************/
//Calculate Integral Image
IntegralImage *  CreateIntegralImage(Uimage8  * src);

inline void DestroyIntegralImage(IntegralImage * img)
{
	free(img->data);
	free(img);
}


//Computes the sum of pixels withing desinated box
inline IntegralDataType BoxIntegral(IntegralImage *image, Int16 row, Int16 col, Uint16 rows,Uint16 cols)
{
	IntegralDataType A,B,C,D;
	Int16 r1, r2, c1,c2;

	Uint32 r1_index, r2_index;
	
	IntegralDataType * data = image->data;

	r1 = _min2(row, image->lines);
	c1 = _min2(col, image->pixels_per_line) + 1;
	r2 = _min2(row + rows, image->lines);
	c2 = _min2(col + cols, image->pixels_per_line) + 1;
	
	r1_index = r1 * (image->pixels_per_line+2);
	r2_index = r2 * (image->pixels_per_line+2);
		
	A = data[r1_index + c1];
	B = data[r1_index + c2];
	C = data[r2_index + c1];
	D = data[r2_index + c2];

	return (((A+D)-B)-C);
}


//! Round float to nearest integer
inline int fRound(float flt)
{
  return (int)floor(flt+0.5f);
}
#endif



